//
//  BookingDetailsViewController.m
//  StraightTrain
//
//  Created by mk on 15/12/2.
//  Copyright © 2015年 mk. All rights reserved.
//

#import "BookingDetailsViewController.h"
#import "PatienUserData.h"
#import "PatientBookingData.h"
#import "PatientAddImagesViewController.h"
#import "PaymentMainViewController.h"

@interface BookingDetailsViewController ()<PatientAddImagesViewControllerDelegate,PaymentMainViewControllerDelegate>
{
    NSMutableArray * arrSummaryPicture;//出院小结
    
    NSMutableArray * arrPictur;
    PatienUserInfoData * patientInfo;
    PatientBookingInfoData * patientBooking;
    NSMutableArray * arrSalesOrder;
    
    BOOL selectMrPicture;//选择病例图片
}

@end

@implementation BookingDetailsViewController


- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    titleLabel.text = @"预约详情";
    arrPictur = [[NSMutableArray alloc]initWithCapacity:0];
    arrSummaryPicture = [[NSMutableArray alloc]initWithCapacity:0];
    
    patientInfo = [[PatienUserInfoData alloc]init];
    patientBooking = [[PatientBookingInfoData alloc]init];
    arrSalesOrder = [[NSMutableArray alloc]initWithCapacity:0];
    
    [self loadDate];
    [self loadPicturData:@"mr"];//病例
    
    if ([self.detailsStatusCode isEqualToString:@"8"] || [self.detailsStatusCode isEqualToString:@"9"])//完成,上传出院小结
    {
       [self loadPicturData:@"dc"];//出院小结
    }
    else//隐藏出院小结
    {
        for (NSLayoutConstraint *constraints in [viewSummary constraints])
        {
            if (constraints.firstItem == viewSummary && constraints.firstAttribute == NSLayoutAttributeHeight)
            {
                constraints.constant = 0;
                break;
            }
        }
    }
    
    [scrollMain setAlwaysBounceVertical:YES];
}

-(void)loadDate
{
    SetHUDStartText(@"加载中..")
    NSString * url = @"";
    if (self.isMySender)
    {
       url = [NSString stringWithFormat:@"%@%@?username=%@&token=%@",[gProjConfig.dicAllUrl objectForKey:@"patientinfoUrl"],self.strPatientId,[gProjConfig.dicUserData objectForKey:USER_tel],[gProjConfig.dicUserData objectForKey:USER_token]];
    }else
    {
      url = [NSString stringWithFormat:@"%@%@?username=%@&token=%@",[gProjConfig.dicAllUrl objectForKey:@"doctorpatientinfoUrl"],self.strPatientId,[gProjConfig.dicUserData objectForKey:USER_tel],[gProjConfig.dicUserData objectForKey:USER_token]];
    }
    
    [[HttpClient manager]GET:url
                  parameters:nil
                     success:^(AFHTTPRequestOperation *operation, id responseObject)
     {
         DLog(@"===%@",responseObject);
         id dateBooking = [[responseObject objectForKey:requestDataKey] objectForKey:@"patientInfo"];
         [patientInfo parseData:dateBooking];
         
         dateBooking = [[responseObject objectForKey:requestDataKey] objectForKey:@"patientBooking"];
         [patientBooking parseData:dateBooking];
         
        dateBooking = [[responseObject objectForKey:requestDataKey] objectForKey:@"salesOrder"];
         if ([dateBooking isKindOfClass:[NSArray class]])
         {
            arrSalesOrder = dateBooking;
         }
         
         [self setDefaultViewData];
         
          SetHUDHidden;
     } failure:^(AFHTTPRequestOperation *operation, NSError *error)
     {
         SetHUDHidden;
         HUDShowRequestError(error.domain, self.view)
     }];
    
}

#pragma mark病例图片 mr病例  dc出院小结
-(void)loadPicturData:(NSString *)strType
{
    //根据入口选择接口
     NSString * strUrl = @"";
    
    if (self.isMySender)
    {
      strUrl = [NSString stringWithFormat:@"%@%@?username=%@&token=%@&report_type=%@",[gProjConfig.dicAllUrl objectForKey:@"patientfileUrl"],self.strPatientId,[gProjConfig.dicUserData objectForKey:USER_tel],[gProjConfig.dicUserData objectForKey:USER_token],strType];
    }else
    {
       strUrl = [NSString stringWithFormat:@"%@%@?report_type=%@&username=%@&token=%@",[gProjConfig.dicAllUrl objectForKey:@"doctorpatientfileUrl"],self.strPatientId,strType,[gProjConfig.dicUserData objectForKey:USER_tel],[gProjConfig.dicUserData objectForKey:USER_token]];
    }
    
     
    [[HttpClient manager]GET:strUrl
                  parameters:nil
                     success:^(AFHTTPRequestOperation *operation, id responseObject)
     {
         if ([strType isEqualToString:@"mr"])//病例
         {
             arrPictur = [responseObject objectForKey:requestDataKey];
             [self setPicturView:viewPictur aryDate:arrPictur];//病例
         }else//出院小结
         {
             arrSummaryPicture = [responseObject objectForKey:requestDataKey];
            int pickerViewH = [self setPicturView:viewSummaryPicture aryDate:arrSummaryPicture];//病例
             
             for (NSLayoutConstraint *constraints in [viewSummary constraints])
             {
                 if (constraints.firstItem == viewSummary && constraints.firstAttribute == NSLayoutAttributeHeight)
                 {
                     constraints.constant = (arrSummaryPicture.count == 0?100:(pickerViewH+50));
                     break;
                 }
             }
            btnSummary.hidden = (arrSummaryPicture.count>0);
         }
         
     } failure:^(AFHTTPRequestOperation *operation, NSError *error)
     {
         HUDShowRequestError(error.domain, self.view)
     }];
    
}

-(void)setDefaultViewData
{
    //支付pay
    int viewPayTypeH = 0;
    //salesOrder
    for (int i = 0; i<arrSalesOrder.count; i++)
    {
        //人民币
       UIButton * btn = [UIButton buttonWithType:UIButtonTypeCustom];
        btn.tag = i;
        btn.frame = CGRectMake(0,viewPayTypeH, viewPayType.width, 45);
        btn.titleLabel.font = [UIFont systemFontOfSize:15];
       [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
       [btn setBackgroundImage:[[UIImage imageNamed:@"booking_pay_bg.png"] stretchableImageWithLeftCapWidth:20 topCapHeight:20] forState:UIControlStateNormal];
       [btn setBackgroundImage:[[UIImage imageNamed:@"booking_pay_bg.png"] stretchableImageWithLeftCapWidth:20 topCapHeight:20] forState:UIControlStateHighlighted];
       [btn addTarget:self action:@selector(btnPayClick:) forControlEvents:UIControlEventTouchUpInside];
       [btn setContentHorizontalAlignment:UIControlContentHorizontalAlignmentLeft];
       [btn setContentEdgeInsets:UIEdgeInsetsMake(0, 20, 0, 0)];
        
        NSMutableDictionary * dicOrder = [[NSMutableDictionary alloc]initWithCapacity:0];
        dicOrder = [arrSalesOrder objectAtIndex:i];
        NSString * strTitle = [NSString stringWithFormat:@"%@:%@",[dicOrder objectForKey:@"subject"],[dicOrder objectForKey:@"finalAmount"]];
        [btn setTitle:strTitle forState:UIControlStateNormal];
       [viewPayType addSubview:btn];
        
        //状态
        UIButton * btnPaid = [UIButton buttonWithType:UIButtonTypeCustom];
        btnPaid.tag = i;
        btnPaid.titleLabel.font = [UIFont systemFontOfSize:15];
        btnPaid.frame = CGRectMake(viewPayType.width-100,viewPayTypeH,100, 45);
        [btnPaid addTarget:self action:@selector(btnPayClick:) forControlEvents:UIControlEventTouchUpInside];
//isPaid
        BOOL isPaid = [[dicOrder objectForKey:@"isPaid"] boolValue];
        if (isPaid)
        {
            [btnPaid setBackgroundColor:UIColorFromRGB(0xAD, 0xAD, 0xAD)];
            [btnPaid setTitle:@"已支付" forState:UIControlStateNormal];
            btnPaid.userInteractionEnabled = NO;
            btn.userInteractionEnabled = NO;
        }else
        {
            [btnPaid setBackgroundColor:defaultNavBackColor];
           [btnPaid setTitle:@"去支付" forState:UIControlStateNormal];
            btnPaid.userInteractionEnabled = YES;
            btn.userInteractionEnabled = YES;
        }
        [viewPayType addSubview:btnPaid];
        
        viewPayTypeH = viewPayTypeH+55;
    }
    
    for (NSLayoutConstraint * constraint in [viewPayType constraints])
    {
        if (constraint.firstItem == viewPayType && constraint.firstAttribute == NSLayoutAttributeHeight)
        {
            constraint.constant = (arrSalesOrder.count==0?0:viewPayTypeH);
        }
    }
    
    for (NSLayoutConstraint * constraint in [viewPay constraints])
    {
        if (constraint.firstItem == viewPay && constraint.firstAttribute == NSLayoutAttributeHeight)
        {
            constraint.constant = (arrSalesOrder.count==0?0:(viewPayTypeH+40));
        }
    }
    
    
    
    //用户基本信息姓名|性别|年龄|地址
    labUser.text = [NSString stringWithFormat:@"%@ | %@ | %@岁 | %@",patientInfo.patien_name,patientInfo.patien_gender,patientInfo.patien_age,patientInfo.patien_cityName];
    // 用户-病情描述
    labDescription.text = [NSString stringWithFormat:@"病情描述:%@",patientInfo.patien_diseaseDetail];
    
    //booking
    
    NSString * strBeg =  [CommonFunctions nianYueRiStringConvertDateString:patientBooking.patien_dateStart withFormatter:@"-"];
    NSString * strEnd = [CommonFunctions nianYueRiStringConvertDateString:patientBooking.patien_dateEnd withFormatter:@"-"];
    
    labTravelTime.text = [NSString stringWithFormat:@"就诊时间:%@至%@",strBeg,strEnd];
    labTravelType.text = patientBooking.patien_travelType;
    labTravelDescription.text =[NSString stringWithFormat:@"%@",patientBooking.patien_detail];

    [scrollMain layoutIfNeeded];
}


#pragma mark 支付界面
-(void)btnPayClick:(id)sender
{
    UIButton * btn = (UIButton *)sender;
    
    PaymentMainViewController * webview = [[PaymentMainViewController alloc]initWithNibName:@"PaymentMainViewController" bundle:nil];
    webview.delegate = self;
    MyNavigationController *navi  = [[MyNavigationController alloc]initWithRootViewController:webview];

    NSString * strUrl = [gProjConfig.dicAllUrl objectForKey:@"paymentUrl"];
    
    NSMutableDictionary * dicOrder = [[NSMutableDictionary alloc]initWithCapacity:0];
    dicOrder = [arrSalesOrder objectAtIndex:btn.tag];
    
    strUrl= [strUrl stringByReplacingOccurrencesOfString:@"refNo=#" withString:[NSString stringWithFormat:@"refNo=%@",[dicOrder objectForKey:@"refNo"]]];
    strUrl= [strUrl stringByReplacingOccurrencesOfString:@"os=#" withString:@"os=ios"];
   
    // DLog(@"==%@",strUrl);
    webview.strUrl = strUrl;
    [self presentViewController:navi animated:YES completion:nil];
    
}

-(void)hidderPayMentMainPaty
{
    [self loadDate];
}


#pragma mark 图片View
-(int)setPicturView:(UIView *)viewImages aryDate:(NSMutableArray *)arryImages
{
    for(UIView * imageP in [viewImages subviews])
    {
        [imageP removeFromSuperview];
    }
    
    int btnWidth = (appScreenWidth-60)/3;
    int row = (int)(arryImages.count/3);
    if (arryImages.count%3>0)
    {
        row = (int)(arryImages.count/3)+1;
    }
    
    int pickerViewH = 0;
    pickerViewH = (btnWidth*row)+(10*row);
    
    for (NSLayoutConstraint *constraints in [viewImages constraints])
    {
        if (constraints.firstItem == viewImages && constraints.firstAttribute == NSLayoutAttributeHeight)
        {
            constraints.constant = pickerViewH;
            break;
        }
    }
    
    //设置view的高度
    int viewWidth = APP_CONTENT_WIDTH;
    
    int btnHeight = (appScreenWidth-50)/3;
    int rowNum = 0;
    int rowRight = 10;
    for (int i = 0; i < [arryImages count]; i++)
    {
        UIButton *btnMark = [UIButton buttonWithType:UIButtonTypeCustom];
        if (viewImages == viewPictur)
        {
          btnMark.tag = i;
        }else
        {
          btnMark.tag = i+100;
        }

        [btnMark addTarget:self action:@selector(btnLookImage:) forControlEvents:UIControlEventTouchUpInside];
        [btnMark setContentMode:UIViewContentModeScaleAspectFill];
        NSString * strImageUrl = [NSString stringWithFormat:@"%@",[[arryImages objectAtIndex:i] objectForKey:@"absThumbnailUrl"]];
        [CommonFunctions setButtonImageWithButton:btnMark iamgePathUrl:strImageUrl];
        
        btnMark.userInteractionEnabled = YES;
        [btnMark setTranslatesAutoresizingMaskIntoConstraints:NO];
        [viewImages addSubview:btnMark];
        
        NSDictionary *views = NSDictionaryOfVariableBindings(btnMark);
        NSString *sH = [NSString stringWithFormat:@"H:|-%d@1000-[btnMark(%d@1000)]",rowRight,btnWidth];
        [viewImages addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:sH
                                                                           options:0
                                                                           metrics:nil
                                                                             views:views]];
        
        NSString *sV = [NSString stringWithFormat:@"V:|-%d@1000-[btnMark(%d@1000)]",rowNum*(btnHeight+10),btnHeight];
        if (i == [arryImages count]-1) {
            sV = [NSString stringWithFormat:@"V:|-%d@1000-[btnMark(%d@1000)]-0@1000-|",rowNum*(btnHeight+10),btnHeight];
        }
        [viewImages addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:sV
                                                                           options:0
                                                                           metrics:nil
                                                                             views:views]];
        rowRight += (btnWidth+10.0f);
        if (rowRight+btnWidth > viewWidth) {
            rowRight = 10.0f;
            rowNum++;
        }
    }
    
    [viewImages.superview layoutIfNeeded];
    
    return pickerViewH;
}



#pragma mark ===查看病例大图图片===
-(void)btnLookImage:(id)sender
{
    UIButton * btn = (UIButton *)sender;
    selectMrPicture = (btn.tag<100);

    MFMWPhotoBrowser * browse = [[MFMWPhotoBrowser alloc] init];
    browse.mfDelegate = self;
    browse.delegate = self;
    browse.displayDeleteButton = NO;
    [browse setCurrentPhotoIndex:(selectMrPicture?btn.tag:btn.tag-100)];
    UINavigationController *nc = [[UINavigationController alloc] initWithRootViewController:browse];
    [self presentViewController:nc animated:YES completion:nil];
    
}


//查看大图
- (NSUInteger)numberOfPhotosInPhotoBrowser:(MWPhotoBrowser *)photoBrowser
{
    if(selectMrPicture)
    {
      return arrPictur.count;
    }else
        return arrSummaryPicture.count;
}

- (MWPhoto *)photoBrowser:(MWPhotoBrowser *)photoBrowser photoAtIndex:(NSUInteger)index
{
    MWPhoto * photo ;
     NSString * strUrl = @"";
    if(selectMrPicture)
    {
       strUrl = [NSString stringWithFormat:@"%@",[[arrPictur objectAtIndex:index] objectForKey:@"absFileUrl"]];
    }else
    {
       strUrl = [NSString stringWithFormat:@"%@",[[arrSummaryPicture objectAtIndex:index] objectForKey:@"absFileUrl"]];
    }
  
    photo = [MWPhoto photoWithURL:[NSURL URLWithString:strUrl]];
    return photo;
    
}

#pragma mark 上传出院小结
-(IBAction)btnAddDcPicture:(id)sender
{
    PatientAddImagesViewController * add = [[PatientAddImagesViewController alloc]initWithNibName:@"PatientAddImagesViewController" bundle:nil];
    add.delegate = self;
    add.strID = self.strPatientId;
    add.strType = @"dc";
    add.addCount = (9-arrSummaryPicture.count);
    [self.navigationController pushViewController:add animated:YES];

}

-(void)addPictureSuccess
{
    [self loadPicturData:@"dc"];//更新出院小结
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end







